import { defineStore } from 'pinia';
import { asyncRoutes, constantRoutes } from '@/router';
import { getRouterList } from '@/api/router';
import { convertRouter, filterAsyncRoutes } from '@/utils/handleRoutes';

export const useRoutesStore = defineStore('router', {
  state: () => ({
    routes: [], // 当前用户的路由
    partialRoutes: [], // 部分路由
  }),
  actions: {
    async setRoutes(permissions) {
      console.log('setRoutes', permissions);
      try {
        // 开源版只过滤动态路由 permissions，admin 不再默认拥有全部权限
        const finallyAsyncRoutes = await filterAsyncRoutes([...asyncRoutes], permissions);
        this.routes = constantRoutes.concat(finallyAsyncRoutes); // 使用 this 更新状态
        return finallyAsyncRoutes;
      } catch (error) {
        console.error('Set Routes Error:', error);
        throw error;
      }
    },

    async setAllRoutes() {
      console.log('setAllRoutes');
      try {
        const { data } = await getRouterList();
        // data.push({ path: '*', redirect: '/404', hidden: true });
        const accessRoutes = convertRouter(data);
        this.routes = constantRoutes.concat(accessRoutes); // 使用 this 更新状态
        return accessRoutes;
      } catch (error) {
        console.error('Set All Routes Error:', error);
        throw error;
      }
    },

    setPartialRoutes(accessRoutes) {
      this.partialRoutes = constantRoutes.concat(accessRoutes); // 使用 this 更新状态
      return this.partialRoutes;
    },
  },
});